﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisBitMapDemo
{
    public class ActiveUserCase
    {
        public void Run()
        {
            var connString = "localhost:6379,defaultDatabase=0,connectTimeout=3000";
            var conn = ConnectionMultiplexer.Connect(connString);
            var db = conn.GetDatabase(0);


            // 单日用户活跃度场景
            // userId 100001,100002,100003...
            // key : ACTIVEUSER:{yyyyMMdd}

            // 设置当日活跃
            // setbit ACTIVEUSER:20220131 1 1
            db.StringSetBit("ACTIVEUSER:20220131", 100001 - 100001, true);

            // 获取用户当日是否活跃
            // getbit ACTIVEUSER:20220131 1
            var ret = db.StringGetBit("ACTIVEUSER:20220131", 100001 - 100001);

            // 获取当日活跃用户数量
            // bitcount ACTIVEUSER:20220131
            var cnt = db.StringBitCount("ACTIVEUSER:20220131");

            // 获取当日所有活跃用户id
            var val = (byte[])db.StringGet("ACTIVEUSER:20220131");

            // 转二进制数组
            var binarySb = new StringBuilder();
            for (int i = 0; i < val.Length; i++)
            {
                binarySb.Append(Convert.ToString(val[i], 2).PadLeft(8, '0'));
            }

            // binarySb = {10000000}
            var binaryIntArray = binarySb.ToString().ToCharArray().Select(o => o == '1' ? 1 : 0).ToArray();
            var activeUserIds = new List<long>();
            for (int i = 0; i < binaryIntArray.Length; i++)
            {
                if (binaryIntArray[i] == 1)
                    activeUserIds.Add(100001 + i);
            }
        }
    }
}
